<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;


class Base extends \think\Controller
{
    protected $_name = '';//数据表名
    protected $menuid = 0;
    protected $list_relation = false;
    protected $_ajaxedit = 0;
    protected $_exclude = '';
    protected $_data = array();
    protected $addAll = false;
    protected $big_menu = false;
    protected $sort = '';
    protected $order = '';
    protected $_editAction = 'edit';
    protected $_delAction = 'delete';
    protected $controller_name;
    protected $action_name;
    protected $del_true = false;//标记是否是软删除
    protected $view_del = false;//是否包含软删除数据
    protected $list_field = '*';
    protected $param_extra = '';//菜单额外参数
    protected $errMsg      = '';
    public function _initialize() {
        $this->checkUser();
        parent::_initialize();
        $this->controller_name = request()->controller();//获取控件器名称
        $this->action_name     = request()->action();//获取方法名
        if(config('ATUO_AUTH_RIGHTS')){
            $this->check(config('ATUO_AUTH_RIGHTS'));//权限验证
        }
        $this->_name  = $this->controller_name;//数据表名 默认获取 子类控制器名称 所以控制器请以表名称命名
        $this->menuid = input('param.menuid/d',0);
        if ($this->menuid) {
            $this->getSubMenu();//获取子菜单
        }
        $this->assign('menuid', $this->menuid);
    }
    public function index(){
        $map = $this->_search();
        $this->_list($map);
        $this->assign('options',$this->check());
        return $this->fetch();
    }
    /**
     * 列表处理
     *
     *
     * @param array $map  条件数据
     * @param string $sort_by  排序字段
     * @param string $order_by  排序方法
     * @param string $field_list 显示字段
     * @param intval $pagesize 每页数据行数
     */
    protected function _list($map = [],  $sort_by='', $order_by='', $pagesize=20){
        //排序
        $model  = model($this->_name);
        $mod_pk = $model->getPk();
        $sort = input('param.sort');
        $order = input('param.order');
        if (!empty($sort_by)) {
            $sort = $sort_by;
        } else if ($this->sort) {
            $sort = $this->sort;
        } else {
            $sort = $mod_pk;
        }
       if (!empty($order_by)) {
            $order = $order_by;
        } else if ($this->order) {
            $order = $this->order;
        } else {
            $order = 'DESC';
        }
        $model->field($this->list_field);
       if($map){
           $model->where($map);
       }
        $model->order($sort.' '.$order);
        $pages = '';
        if($pagesize){
            $list  = $model->paginate($pagesize);//分页
            $pages = $list->render();

        }else{
            $list = $model->select();
        }
        $this->assign('pages',$pages);
        $this->assign('list', $list);
        $this->assign('list_table', true);
    }
    protected function _search(){
        return [];
    }

    //添加方法
    public function add(){
        if(request()->isAjax()){
            $response = $this->fetch();
            $this->ajaxReturn(1,'',$response);
        }else{
            return $this->fetch();
        }
    }
    //执行添加操作
    public function addDo(){
        $obj = model($this->_name);
        if(request()->isPost()){
            $data = input('post.');
            $img  = $this->_uploadImg();
            if($img){
                $data['img'] = $img;
            }
            if($obj->allowField(true)->save($data)){
                request()->isAjax() ? $this->ajaxReturn(1,'添加成功','','add') : $this->success('添加成功');
            }else{
                request()->isAjax() ? $this->ajaxReturn(0,'添加失败','') : $this->error('添加失败');
            }
        }
    }
    //编辑
    public function edit(){
            $obj = model($this->_name);
            $pk  = $obj->getPk();
            $id  = input($pk);
            if($id){
                if($this->view_del){//包含软删除数据
                    $obj = $obj::withTrashed();
                }
                $info = $obj->find($id);
                $this->assign('info',$info);
                if(request()->isAjax()){
                    $response = $this->fetch();
                    $this->ajaxReturn(1,'',$response);
                }else{
                    return $this->fetch();
                }
            }else{
                request()->isAjax() ? $this->ajaxReturn(0,'参数错误') : $this->error('参数错误');
            }

    }
    //保存编辑内容
    public function editDo(){
        $obj = model($this->_name);
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['id']) || empty($data['id'])){
                request()->isAjax() ? $this->ajaxReturn(0,'参数错误') : $this->error('参数错误');
            }
            $img = $this->_uploadImg();
            if($img){
                $data['img'] = $img;
            }
            //allowField 过滤非数据表字段
            if($obj->allowField(true)->save($data,['id'=>$data['id']]) || $this->errMsg === true){
                request()->isAjax() ? $this->ajaxReturn(1,'编辑成功','','edit') : $this->success('编辑成功');
            }else{
                request()->isAjax() ? $this->ajaxReturn(0,'编辑失败','') : $this->error('编辑失败');
            }
        }
    }
    /**
     * ajax修改单个字段值
     */
    public function ajaxEdit()
    {
        //AJAX修改数据
        $mod = model($this->_name);
        $pk  = $mod->getPk();
        $id  = input($pk);
        $field = input('param.field');
        $val   = input('param.val');
        $mod->where([$pk=>$id])->setField($field, $val);
        $this->ajaxReturn(1);
    }
    /**
     * 删除
     */
    public function delete(){
        $mod = model($this->_name);
        $pk  = $mod->getPk();
        $ids = trim(input($pk), ',');
        if ($ids) {
            if (0 !== $mod::destroy($ids,$this->del_true)) {
                request()->isAjax() && $this->ajaxReturn(1, '删除成功');
                $this->success('删除成功');
            } else {
                $str = $this->errMsg ? $this->errMsg : '删除失败';
                request()->isAjax() && $this->ajaxReturn(0, $str);
                $this->error('删除失败');
            }
        } else {
            request()->isAjax() && $this->ajaxReturn(0, '参数错误');
            $this->error('参数错误');
        }
    }
    //获取 子菜单
    private function getSubMenu(){
        $sub_menu = [];
        $sub_menu = model('menu')->subMenu($this->menuid, $this->big_menu);
        $selected = '';
        if($sub_menu){
            $param['menuid'] = $this->menuid;
            if($this->param_extra){
                $param = array_merge($param,$this->param_extra);
            }
            foreach ($sub_menu as $key=>$val) {
                $sub_menu[$key]['class'] = '';
                if ($this->controller_name == $val['module_name'] && $this->action_name == $val['action_name']) {
                    $sub_menu[$key]['class'] = $selected = 'on';
                }
                $sub_menu[$key]['url'] = url($val['module_name'].'/'.$val['action_name'],$param).$val['data'];
            }
            if (empty($selected)) {
                foreach ($sub_menu as $key=>$val) {
                    if ($this->controller_name == $val['module_name'] && $this->action_name == $val['action_name']) {
                        $sub_menu[$key]['class'] = 'on';
                        break;
                    }
                }
            }
        }
        $this->assign('sub_menu', $sub_menu);
    }
    //异步上传图片
    public function ajaxUploadImg(){
        $img = $this->_uploadImg();
        if($img){
            $this->ajaxReturn(1,'上传成功',$img);
        }else{
            $this->ajaxReturn(0,'请选择图片');
        }
    }
    private function _uploadImg(){
        $img = '';
        if(isset($_FILES['img']) && !empty($_FILES['img']['name'])){
            $file = request()->file('img');
            // 移动到框架应用根目录/public/uploads/ 目录下
            $path = config('uploads_path').$this->controller_name.'/';
            $info = $file->move(ROOT_PATH.$path);
            if($info){
                $img = '/uploads/'.$this->controller_name.'/'.str_replace('\\','/',$info->getSaveName());
            }else{
                // 上传失败获取错误信息
                request()->isAjax() ? $this->ajaxReturn(0,$file->getError()) : $this->error($file->getError());
            }
        }
        return $img;
    }
    private function checkUser(){
        if(!session('adminInfo')){
            $this->redirect('Login/index');
        }
    }
    protected function ajaxReturn($status=0,$msg='',$data='',$id=''){
        $return['status'] = $status;
        $return['msg']    = $msg;
        $return['data']   = $data;
        $return['dialog'] = $id;//用于关闭弹出框
        header('Content-Type:text/html; charset=utf-8');
        exit(json_encode($return));
    }
    /**
     * @param bool $isauto 是否是自动验证 默认为手动验证
     * @param array $data = array(
     *                              'c'=>要验证的控制器名称
     *                              'a'=>要验证的方法名称
     *                              'str'=>返回的字符串 (其中url请用%s替代 不设置将返回空)
     *                              'replace'=>可选 （如果木有权限的时候返回的提示字符 默认返回无权限）
     *                              'param'=>url参数变量用@id@（固定格式）替代 该参数将会附到url链接中
     *                             )
     * @exclude string; 排除默认列表中的值
     * @param string $returntype 返回的类型 默认返回字符串 取值str|arr arr返回数组
     * @return array|string
     */
    protected function check($isauto=false,$returntype='str'){
        //如果是自动验证
        $return = '';
        $editstr = '<a href="%s">编辑</a>';
        $editajax = '<a data-height="400" data-width="500" data-id="edit" data-uri="%s" data-title="编辑 - %s" class="J_showdialog" href="javascript:;">编辑</a>';
        $default = array(
            'edit'    => array(
                'c' => $this->controller_name,
                'a' => $this->_editAction,
                'str'    => '',
                'param' => array('id'=>'@id@'),
                'isajax' => $this->_ajaxedit,
                'replace'=> ''
            ),
            'delete' => array(
                'c'   => $this->controller_name,
                'a'   => $this->_delAction,
                'param' => array('id'=>'@id@'),
                'str' => '<a data-uri="%s" data-msg="确定要删除 %s 吗？" data-acttype="ajax" class="J_confirmurl" href="javascript:void(0);">删除</a>',
                'isajax'  => 1,
                'replace' => ''
            )
        );
        $optionarr = array('edit','delete');
        if(!empty($this->_exclude) && in_array($this->_exclude,$optionarr)){
            unset($default[$this->_exclude]);
        }
        if($isauto){
            $c = $this->controller_name;
            $a = $this->action_name;
            if(!\org\Role::check($c,$a)){
                request()->isAjax() ? $this->ajaxReturn(0,'无权限操作','无权限操作') : $this->error('无权限操作');
            }
        }else{
            if(empty($this->_data)){
                $data = $default;
            }else{
                $data = array_merge($this->_data,$default);
            }
            $return = [];
            //二维数组的处理方法
            foreach($data as $k=>$v){
                $c     = $v['c'];
                $a     = $v['a'];
                $param = $v['param'];
                if(!isset($param['menuid'])){
                    $param['menuid'] = '@menuid@';
                }
                if($this->param_extra){
                    $param = array_merge($param,$this->param_extra);
                }
                $str   = $k=='edit' ? ($v['isajax']==1 ? $editajax : $editstr) : $v['str'];
                $replace = isset($v['replace']) && !empty($v['replace']) ? $v['replace'] : '无权限';
                if(\org\Role::check($c,$a)){
                    $return[] = sprintf($str,urldecode(url($c.'/'.$a,$param)),'@name@');
                }else{
                    $return[] = '<span class="disabled-link">'.$replace.'</span>';
                }
            }
            if($returntype == 'str'){
                $return = implode(' | ',$return);
            }
            return $return;
        }

    }
}